<script setup lang="ts">
import { ref, defineEmits, watch } from "vue"
import { ElForm, ElFormItem, ElInput, ElDialog, ElButton } from "element-plus"
import type { PropType } from 'vue'
import type { FormInstance } from 'element-plus'
import { debounceFn } from "#/utils/debounce"
import { addPaperApi } from '#/api/manage/paper'
import { getCertifiedListApi } from "#/api/certificate/list"
import { trimStringParams } from '#/utils/trimStringParams'
import { $t } from '@vben/locales';
defineOptions({ name: 'Dialog' })
interface ModelValueType {
  dialogVisible: boolean;
}

const props = defineProps({
  modelValue: {
    type: Object as PropType<ModelValueType>,
    required: true
  }
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const submitLoading = ref(false)

const ruleForm = ref({
  examTitle: '',
  totalPaper: null,
  certificateId: null
})

const certificateList = ref<any>([])

const rules = {
  examTitle: [
    { required: true, message: $t('common.inputPhTxt', [$t('paper.paperNameTxt')]), trigger: ['blur', 'change'] },
  ],
  totalPaper: [
    { required: true, message: $t('common.inputPhTxt', [$t('paper.totalPaperTxt')]), trigger: 'blur' }
  ],
  certificateId: [
    { required: true, message: $t('common.selectPhTxt', [$t('paper.certificateTxt')]), trigger: 'change' }
  ]
}

const emit = defineEmits(['updateList']);
const handleClose = () => {
  ruleForm.value = {
    examTitle: '',
    totalPaper: null,
    certificateId: null
  }
  formRef.value?.resetFields()
  props.modelValue.dialogVisible = false
}

const getTabelData = () => {
  const params = {
    curPage: 1,
    pageSize: 10000
  } as any
  loading.value = true
  getCertifiedListApi(params).then(res => {
    let { data } = res;
    console.log(data)
    certificateList.value = data.map((_: { id: any, name: any }) => { return { id: _.id, name: _.name } })
  }).finally(() => {
    loading.value = false
  })
}

const onChangeCertificate = (val: any) => {
  const certificate = certificateList.value.find((_: any) => _.id === val)
  ruleForm.value.examTitle = !!certificate ? `${certificate.name}试卷` : ''
}

const submitQuestion = debounceFn(() => {
  if (!formRef) return
  formRef.value?.validate((valid) => {
    if (valid) {
      const { examTitle, totalPaper, certificateId } = ruleForm.value
      const params = {
        examPapersName: examTitle,
        totalPaper: totalPaper,
        certificateId
      }
      submitLoading.value = true
      addPaperApi(trimStringParams(params)).then(() => {
        submitLoading.value = false
        handleClose()
        emit('updateList')
      }).catch(() => {
        submitLoading.value = false
      })
    }
  })
}, 300, true)

watch(props.modelValue, () => {
  if (props.modelValue.dialogVisible) {
    console.log(1234)
    getTabelData()
  }
})

</script>
<template>
  <el-dialog v-model="modelValue.dialogVisible" align-center :title="$t('common.newTxt')" width="500"
    :close-on-click-modal="false" :before-close="handleClose">
    <div class="">
      <el-form v-loading="loading" ref="formRef" class="w-[100%]" :model="ruleForm" :rules="rules" label-width="80px"
        label-position="left">
        <el-form-item :label="$t('paper.certificateTxt')" prop="certificateId">
          <el-select @change="onChangeCertificate" clearable v-model="ruleForm.certificateId"
            :placeholder="$t('common.selectPhTxt', [$t('paper.certificateTxt')])">
            <el-option v-for="item in certificateList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('paper.paperNameTxt')" prop="examTitle" style="margin-bottom: 20px !important;">
          <el-input type="text" :maxlength="50" class="w-[100%]" v-model="ruleForm.examTitle"
            :placeholder="$t('common.inputPhTxt', [$t('paper.paperNameTxt')])"></el-input>
        </el-form-item>
        <el-form-item :label="$t('paper.totalPaperTxt')" prop="totalPaper" style="margin-bottom: 20px !important;">
          <el-input type="number" :maxlength="10" class="w-[100%]" :min="0" v-model="ruleForm.totalPaper"
            :placeholder="$t('common.inputPhTxt', [$t('paper.totalPaperTxt')])"></el-input>
        </el-form-item>

      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancelTxt') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitQuestion">
          {{ $t('common.submitTxt') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
